package com.atguigu.springcloud.service;


import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class HystrixService {

    //正常程序
    public String paymentInfo_OK(Long id){
        String str="线程池："+Thread.currentThread().getName()+"paymentOK,Id: "+id;
        return str;
    }
    //耗时3秒程序
    @HystrixCommand(fallbackMethod = "paymentInfo_Timeout_Handler",commandProperties = {
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000")
    })
    public String paymentInfo_Timeout(Long id){
        //假设程序执行要5秒种，而hystrix设置在超过三秒钟之后就会实现服务降级，实施兜底方案
        int timeout=5;
        try {
            TimeUnit.SECONDS.sleep(timeout);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String str="线程池："+Thread.currentThread().getName()+"paymentTimeout,Id: "+id+" 耗时"+timeout+"秒钟";
        return str;
    }
    //兜底方案
    public String paymentInfo_Timeout_Handler(Long id){
        String str="线程池："+Thread.currentThread().getName()+"系统繁忙请稍后再试,Id: "+id+"/(ㄒoㄒ)/~~";
        return str;
    }

//====服务熔断====
    /**
     * 意义：在10秒窗口期中如果10次请求中有6次请求失败的话,断路器将起作用，实现服务熔断
     *
     * @param id
     * @return
     */
    @HystrixCommand(
            fallbackMethod = "paymentCircuitBreaker_fallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),// 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),// 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "20000"),// 时间窗口期/时间范文
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")// 失败率达到多少后跳闸
    }
    )
    public String paymentCircuitBreaker(Long id) {
        if (id < 0) {
            throw new RuntimeException("*****id不能是负数");   //执行回滚方法
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "调用成功,流水号:" + serialNumber;
    }

    public String paymentCircuitBreaker_fallback(Long id) {
        return "id 不能负数,请稍后重试,o(╥﹏╥)o id:" + id;
    }

}
